#!/usr/bin/env python

from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import users

class UserModel(db.Model):
  """Deriveable class used to store information associated with a user.

  Subclasses can add properties like a regular db.Model class, and call
  get_for_current_user() to retrieve the UserModel record associated with the
  current user (or insert a new record if one does not exist)."""
  user = db.UserProperty(auto_current_user=True)

  @classmethod
  def get_for_current_user(cls, user=None, **kwds):
    """Gets the UserModel instance associated with the current user.

    This will also insert a new UserModel record if one is not already
    associated with the current user. Arguments passed as keywords will be set
    on this new instance if this is the case."""
    if not user:
      user = users.get_current_user()
    if not user:
      return None #TODO esplode!
    model = memcache.get(user.user_id())
    if model is not None:
      return model
    return cls.get_or_insert(user.user_id(), **kwds)

  def put(self):
    """Persists the current instance in memcache and datastore."""
    memcache.add(self.user.user_id(), self)
    db.put(self)

class AppUser(UserModel):
  items_completed = db.IntegerProperty(default=0)

class WorkItem(db.Model):
  prompt = db.StringProperty(required=True)
  result = db.StringProperty()

class Task(db.Model):
  owner = db.UserProperty(auto_current_user=True)
  created = db.DateTimeProperty(auto_now_add=True)
  updated = db.DateTimeProperty(auto_now=True)
  random = db.FloatProperty(required=True)
  script = db.TextProperty(required=True)
  todo = db.ListProperty(db.Key, default=[])
  done = db.ListProperty(db.Key, default=[])